//! \file WindowConsole.cpp
//! \brief TODO: Document
// -----------------------------------------------------------------------------
//! This program is free software; you can redistribute it and/or
//! modify it under the terms of the GNU General Public License
//! as published by the Free Software Foundation; either version 2
//! of the License, or (at your option) any later version.
//!
//! This program is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with this program; if not, write to the Free Software Foundation,
//! Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
// -----------------------------------------------------------------------------

#include "Elements.h"
#include "GuiCEGUI.h"
#include <stddef.h>

using namespace CEGUI;

// =====[ Local Definitions ]===================================================

// =====[ Local DataTypes ]=====================================================

// =====[ Local Variables ]=====================================================
int WindowConsole::m_HistoryPosition = 0;
std::vector<CEGUI::String> WindowConsole::m_History;

// =====[ Local Functions ]=====================================================

// =====[ Private (Internal) Methods ]==========================================

// =====[ Local Implementation ]================================================


// =============================================================================
// FxName
// -----------------------------------------------------------------------------
//! TODO: document
//!
//! \param [in] Arg
//!   TODO: document
//!
//! \retval Exception
//!   The success status of the requested operation.
//!   - eOKAY: Execution occurred as requested.
//!   .
//!
//! \b Example: \code
//! FxName(0);
//! \endcode
// -----------------------------------------------------------------------------
tERROR WindowConsole::create(Window *pParent)
{
//  Window *pWindow;

  // We can only create one console window.
  if (createSingle(pParent) == false)
    { return (ERR_GUI_UNABLE_TO_CREATE); }

// TODO: remove
//  if (m_pParent != NULL)
//    { return (ERR_GUI_UNABLE_TO_CREATE); }
//
//  // Determine and save our singleton parent.
//  if (pParent != NULL)
//    { m_pParent = pParent; }
//  else
//    { m_pParent = GuiCEGUI::getRoot(); }

  // Load the console window layout and add it to the parent.
  m_pParent->addChildWindow(GuiCEGUI::getWm()->loadWindowLayout("DQ_Console.layout"));

  // Submit button.
  subscribeEvent("Console/Submit", PushButton::EventClicked, SubscriberSlot(&eventSubmit));

  // Clear button.
  subscribeEvent("Console/Clear", PushButton::EventClicked, SubscriberSlot(&eventClear));


//  m_pParent
//
//  Editbox* pEditBox = static_cast<Editbox*>(pParent->getChild("Console/Input"));

//  // Quit button
//  subscribeEvent("TextDemo/Quit", PushButton::EventClicked, Event::Subscriber(&TextDemo::quit, this));

  /*// Create the window.
  pWindow = GuiCEGUI::getWm()->createWindow("TaharezLook/FrameWindow");
  if (pWindow == NULL) {  TODO: error  }

  // Configure the window as needed.
  pWindow->setText("Console");
  pWindow->setAlwaysOnTop(true);      // Keep it on top.



//  <Property Name="UnifiedMinSize" Value="{{0.2,0},{0.2,0}}"/>
//  <Property Name="UnifiedMaxSize" Value="{{0.8,0},{0.8,0}}"/>

  // Position the console window at the bottom of the screen.
  pWindow->setPosition(UVector2(UDim(0.0f, 0.0f), UDim(0.7f, 0.7f)));

  // Set the console window size to be half the size of the parent.
  pWindow->setSize(UVector2(UDim(1.0f, 0.3f), UDim(0.3f, 1.0f)));*/

//  pWindow->set

//  pWindow->setMaxSize()
//  pWindow->setMinSize()

//  pWindow->

//  <Property Name="UnifiedPosition" Value="{{0.5,0},{0.5,0}}"/>
//  <Property Name="UnifiedSize" Value="{{0.5,0},{0.45,0}}"/>
//  <Property Name="Text" Value="Console"/>
//  <Property Name="CloseButtonEnabled" Value="False"/>

//  // Configure the menu bar as needed.
//  pWindow->setModalState(true);
//  pWindow->setAlpha(0.5f);

  // TODO: clean below the line ----------------------------




//  pParent->addChildWindow(pWindow);   // Attach it to the parent.

  // Finally, return no error.
  return (ERR_NONE);
}


// =============================================================================
// FxName
// -----------------------------------------------------------------------------
//! TODO: document
//!
//! \param [in] Arg
//!   TODO: document
//!
//! \retval Exception
//!   The success status of the requested operation.
//!   - eOKAY: Execution occurred as requested.
//!   .
//!
//! \b Example: \code
//! FxName(0);
//! \endcode
// -----------------------------------------------------------------------------
tERROR WindowConsole::appendText(CEGUI::String& Text)
{
  MultiLineEditbox* pHistoryBox;

  // Ensure we've been initialized.
  if (m_pParent == NULL)
  { return (ERR_GUI_ELEMENT_UNINITIALIZED); }

  // Check if there is any text to append.
  if (Text.empty() == true)
    { return (ERR_NONE); } // Return success.

  // Add this entry to the command history buffer.
  m_History.push_back(Text);

  // Reset history position.
  m_HistoryPosition = m_History.size();

  // Append newline to this entry.
  Text+= '\n';

  // Get history window.
  pHistoryBox = static_cast<MultiLineEditbox*>(m_pParent->getChild("Console/History"));

  // Append new text to history output.
  pHistoryBox->setText(pHistoryBox->getText() + Text);

  // Scroll to bottom of history output.
  pHistoryBox->setCaratIndex(static_cast<size_t>(-1));

  // Return success.
  return (ERR_NONE);
}


bool WindowConsole::eventSubmit(const CEGUI::EventArgs& Event)
{
//    // signal quit
//    d_sampleApp->setQuitting();
  puts("Submit");

  Window *pRoot = GuiCEGUI::getRoot();

  // Get the edit box that is providing the text input.
  Window* pParent = static_cast<Window*>(pRoot->getChild("Console"));
//  Editbox* pEditBox = static_cast<Editbox*>(pRoot->getChild("Console/Input"));
  Editbox* pEditBox = static_cast<Editbox*>(pParent->getChild("Console/Input"));

  // Get the input text from the edit box.
  String Text(pEditBox->getText());

  // If there is no input, nothing left to do.
  if (Text.empty() == true)
    { return (true); } // Return the event was handled.

  // Add this entry to the command history buffer.
  m_History.push_back(Text);

  // Reset history position.
  m_HistoryPosition = m_History.size();

  // Append newline to this entry.
  Text += '\n';

  // Get history window.
//  MultiLineEditbox* history = static_cast<MultiLineEditbox*>(pRoot->getChild("Console/History"));
  MultiLineEditbox* history = static_cast<MultiLineEditbox*>(pParent->getChild("Console/History"));

  // Append new text to history output.
  history->setText(history->getText() + Text);

  // Scroll to bottom of history output.
  history->setCaratIndex(static_cast<size_t>(-1));

  // Erase text in text entry box.
  pEditBox->setText("");

  // Reactivate the text entry box.
  pEditBox->activate();

  return true;



//  // get the text entry editbox
//  Editbox* editbox = static_cast<Editbox*>(d_root->getChild(EntryBoxID));
//  // get text out of the editbox
//  String edit_text(editbox->getText());
//  // if the string is not empty
//  if (!edit_text.empty())
//  {
//      // add this entry to the command history buffer
//      d_history.push_back(edit_text);
//      // reset history position
//      d_historyPos = d_history.size();
//      // append newline to this entry
//      edit_text += '\n';
//      // get history window
//      MultiLineEditbox* history = static_cast<MultiLineEditbox*>(d_root->getChild(HistoryID));
//      // append new text to history output
//      history->setText(history->getText() + edit_text);
//      // scroll to bottom of history output
//      history->setCaratIndex(static_cast<size_t>(-1));
//      // erase text in text entry box.
//      editbox->setText("");
//  }














  // Return the event was handled.
  return (true);
}


bool WindowConsole::eventClear(const CEGUI::EventArgs& Event)
{
//  // signal quit
//  d_sampleApp->setQuitting();

  puts("Clear");

  // Return the event was handled.
  return (true);
}


/*

tERROR WindowConsole::addButtonSubmit(Window *pParent)
{
  Window *pWindow;

  // If no parent was provided, we will attach it to the root.
  if (pParent == NULL) { pParent = GuiCEGUI::getRoot(); }

  // Create the window.
  pWindow = GuiCEGUI::getWm()->createWindow("TaharezLook/Button");
  if (pWindow == NULL) {  TODO: error  }

  // Configure the window as needed.
  pWindow->setText("Console/Submit");
//  pWindow->setAlwaysOnTop(true);      // Keep it on top.

  // Position the console window at the bottom of the screen.
  pWindow->setPosition(UVector2(UDim(0.0f, 0.0f), UDim(0.7f, 0.7f)));

//  // Set the console window size to be half the size of the parent.
//  pWindow->setSize(UVector2(UDim(1.0f, 0.3f), UDim(0.3f, 1.0f)));


//  <Window Type="Vanilla/Button" Name="Vanilla/Console/Submit">
//    <Property Name="ID" Value="1"/>
//    <Property Name="VerticalAlignment" Value="Bottom"/>
//    <Property Name="HorizontalAlignment" Value="Right"/>
//    <Property Name="UnifiedMaxSize" Value="{{1,0},{1,0}}"/>
//    <Property Name="UnifiedPosition" Value="{{0,-7},{0,-7}}"/>
//    <Property Name="UnifiedSize" Value="{{0.25,0},{0,30}}"/>
//    <Property Name="Text" Value="Submit"/>
//  </Window>

  // Attach to the parent.
  pParent->addChildWindow(pWindow);

  // Return success.
  return (ERR_NONE);
}
*/


